'use strict';
const { fileHash } = require('../utils/constant');
const { validInvalidUrlFn } = require('../utils/tools');
const Service = require('egg').Service;

class commonInfoService extends Service {
  // [ 'hash', 'fileName' ]
  // 检查是否重复
  async duplicate(arr) {
    const temp = {};
    const list = [];
    for (let i = 0; i < arr.length; i++) {
      const itemObj = arr[i];
      console.log(itemObj, 'itemObj');
      for (const key in itemObj) {
        if (Object.hasOwnProperty.call(itemObj, key)) {
          if (key === 'filename') {
            continue;
          }
          const value = itemObj[key];
          if ([ 'hash', 'fileName' ].includes(key)) {
            if (temp[key] === value) {
              list.push(`第${i + 1}行,${fileHash[key]};`);
            }
            temp[key] = value;
            if (key === 'hash') {
              if (await this.compareHash({ hash: value })) {
                list.push(`第${i + 1}行,文件已存在数据库中;`);
              }
            } else if (await this.compareHash({ fileName: value })) {
              list.push(`第${i + 1}行,文件名已存在数据库中;`);
            }
          }
          if (key === 'relatedUrl' && !validInvalidUrlFn(value)) { // 相关地址
            list.push(`第${i + 1}行,${fileHash[key]}`);
          }
        }
      }
    }
    return list;
  }
  // 文件md5比较
  async compareHash(where) {
    const { ctx } = this;
    const hasId = await ctx.model.File.findOne({
      attributes: [ 'id' ],
      where,
    });
    return !!hasId;
  }
}

module.exports = commonInfoService;
